﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Warehouse.Application.Dto.Input;
using Warehouse.Application.Dto.Output;
using Warehouse.Domain.Entities;
using Warehouse.Infrastructure.Repositories;
using Warehouse.Result;
using Yitter.IdGenerator;

namespace Warehouse.Application.Services.Storage
{
    public class StorageAppService:IStorageAppService
    {
        private readonly IWarehouseModelRepository<StorageModel> _storageRepository;
        private readonly IMapper _mapper;
        private readonly IWarehouseModelRepository<WareHouseModel> _warehouseRepository;

        public StorageAppService(IWarehouseModelRepository<StorageModel> storageRepository, IMapper mapper, IWarehouseModelRepository<WareHouseModel> warehouseRepository)
        {
            _storageRepository = storageRepository;
            _mapper = mapper;
            _warehouseRepository = warehouseRepository;
        }


        /// <summary>
        /// 创建货架/库区
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> CreateStore(CreateStoreInput input)
        {
            var model =_mapper.Map<StorageModel>(input);
            model.Id = YitIdHelper.NextId();
            model.CreatedAt = DateTime.Now;
            model.IsDeleted = false;

            // 获取当前日期并格式化为yyyyMMdd
            string dateStr = DateTime.Now.ToString("yyyyMMdd");

            // 查询当天已有的记录数
            string prefix = "ST" + dateStr;
            var todayItems = _storageRepository.GetValue()
                .Where(x => x.StorageCoding != null &&
                            x.StorageCoding.StartsWith(prefix) &&
                            x.CreatedAt.Date == DateTime.Now.Date)
                .ToList();

            // 计算序号
            int sequence = todayItems.Count + 1;

            // 生成编码
            string coding = $"{prefix}{sequence:D4}";
            model.StorageCoding = coding;


            _storageRepository.Create(model);
            return new ApiResult<int>()
            {
                Code = ApiEnum.Ok,
                Message = "添加货架成功",
                Data = 1
            };

        }


        /// <summary>
        /// 获取货架/库区列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiPaing<StorageOutput> GetStorage(PageInput input)
        {
            var stor =_storageRepository.GetValue().Where(x => x.IsDeleted == false);
            var ware =_warehouseRepository.GetValue().Where(x => x.IsDeleted == false);
            var linq =from a in stor join
                      b in ware on  a.WareHouseId equals b.Id
                      select new StorageOutput()
                      {
                          Id = a.Id,
                          StorageCoding = a.StorageCoding,
                          StorageName = a.StorageName,
                          WareHouseId = a.WareHouseId,
                          WareHouseCoding = b.WareHouseCoding,
                          WareHouseName = b.WareHouseName,
                          StorageDescribe = a.StorageDescribe,
                          CreatedAt =a.CreatedAt,
                          CreatedBy = a.CreatedBy,
                          UpdatedAt = a.UpdatedAt,
                          UpdatedBy = a.UpdatedBy
                      };
            var list =linq.OrderByDescending(x => x.Id).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
            return new ApiPaing<StorageOutput>
            {
                TotalCount = list.Count(),
                PageDatas = list,
                Code = ApiEnum.Ok,
                Message = "查询成功"
            };
        }

        /// <summary>
        /// 所属仓库下拉
        /// </summary>
        /// <returns></returns>
        public ApiPaing<WareHouseModel> GetAllWareHouse()
        {
            var list = _warehouseRepository.GetValue().Where(x => x.IsDeleted == false).ToList();
            return new ApiPaing<WareHouseModel>
            {
                TotalCount = list.Count,
                PageDatas = list,
                Code = ApiEnum.Ok,
                Message = "查询成功"
            };
        }


        /// <summary>
        /// 删除货架/库区详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> DeltetStorage(long Id)
        {
            var list =_storageRepository.GetValue().FirstOrDefault(x => x.Id == Id && x.IsDeleted==false);
            if (list == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Fail,
                    Message = "未找到数据"
                };
            }
            list.IsDeleted = true;
            _storageRepository.Update(list);
            return new ApiResult<int>
            {
                Code = ApiEnum.Ok,
                Message = "删除成功",
                Data = 1
            };

        }


        /// <summary>
        /// 修改货架/库区详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateStorage(UpdateStorageInput input)
        {
            var list =_storageRepository.GetValue().FirstOrDefault(x => x.Id == input.Id && x.IsDeleted==false);
            if (list == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Fail,
                    Message = "未找到数据"
                };
            }
            var model = _mapper.Map(input, list);
            model.UpdatedAt = DateTime.Now;
            _storageRepository.Update(model);
            return new ApiResult<int>
            {
                Code = ApiEnum.Ok,
                Message = "修改成功",
                Data = 1
            };



        }



        /// <summary>
        /// 获取一条货架/库区详情用来回显操作
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
       public ApiResult<StorageModel> GetModelStorage(long Id)
        {
            var list =_storageRepository.GetValue().FirstOrDefault(x => x.Id == Id && x.IsDeleted==false);
            if(list == null)
            {
                return new ApiResult<StorageModel>
                {
                    Code = ApiEnum.Fail,
                    Message = "未找到数据"
                };
            }
            return new ApiResult<StorageModel>
            {
                Code = ApiEnum.Ok,
                Message = "查询成功",
                Data = list
            };
        }


    }
}
